from turbogears import controllers, expose, flash, validate, error_handler, \
                       exception_handler, url
from model import *
from turbogears import identity, redirect, i18n
from cherrypy import request, response
from forms import *
from sqlobject import sqlbuilder
from cgi import escape
import breadcrumbs

# from tgsampleapp import json
# import logging
# log = logging.getLogger("tgsampleapp.controllers")

def event_url(event):
    """Get Event URL"""
    return url('/event/%s' % event.id)

class Root(controllers.RootController):

    def events_by_city(self):
        conn = Event._connection
        for i in conn.queryAll(conn.sqlrepr(sqlbuilder.Select(Event.q.city, groupBy=Event.q.city))):
            yield {'title':i,
                 'events': (k for k in Event.select(Event.q.city==i))}

    @expose(template="tgsampleapp.templates.list")
    # @identity.require(identity.in_group("admin"))
    def list(self):
        """Event List"""
        return dict(cities=self.events_by_city(),
                    title="List of Events",
                    event_url=event_url)

    @expose()
    # @identity.require(identity.in_group("admin"))
    def index(self):
        """Index"""
        return self.map()

    @expose()
    def change_lang(self, lang):
        """Change language"""
        i18n.set_session_locale(lang)
        return response.redirect(request.referer)

    @expose(template="tgsampleapp.templates.form")
    def add(self, tg_errors=[]):
        """Show the event form."""

        if tg_errors:
            flash('There was a problem with the form!')
        return dict(form=event_add_form,
                    title="Add an event",
                    label="Event",
                    obj=None)

    @expose()
    @validate(form=event_add_form)
    @error_handler(add)
    def save_created(self, **kw):
        """Handle submission from the comment form and save the event."""
        event = Event(**kw)
        flash('Event added!')
        redirect(event_url(event))


    @expose(template="tgsampleapp.templates.form")
    # @identity.require(identity.in_group("admin"))
    def event(self, event_id):
        """Event Details"""
        event = Event.get(event_id)
        return dict(form=event_display_form,
                    title="Details of Event",
                    label="Event",
                    obj=event)

    @expose(template="tgsampleapp.templates.form")
    # @identity.require(identity.in_group("admin"))
    def map(self):
        """Map of Events"""
        return dict(form=event_map_form,
                    title="Map of Events",
                    label="Map of Events",
                    obj=None)

    @expose(template="tgsampleapp.templates.list_kml", format="xml")
    def list_kml(self):
        """KML for map of events"""
        response.headers['Content-Type']='application/vnd.google-earth.kml+xml kml'
        return dict(events=Event.select(),
                    form=event_short_display_form,
                    event_url=event_url,
                    escape=escape)

    @expose(template="tgsampleapp.templates.login")
    def login(self, forward_url=None, previous_url=None, *args, **kw):

        if not identity.current.anonymous \
            and identity.was_login_attempted() \
            and not identity.get_identity_errors():
            raise redirect(forward_url)

        forward_url=None
        previous_url= request.path

        if identity.was_login_attempted():
            msg=_("The credentials you supplied were not correct or "
                   "did not grant access to this resource.")
        elif identity.get_identity_errors():
            msg=_("You must provide your credentials before accessing "
                   "this resource.")
        else:
            msg=_("Please log in.")
            forward_url= request.headers.get("Referer", "/")

        response.status=403
        return dict(message=msg, previous_url=previous_url, logging_in=True,
                    original_parameters=request.params,
                    forward_url=forward_url)

    @expose()
    def logout(self):
        identity.current.logout()
        raise redirect("/")
